package com.ljh.mall.controller;

import com.ljh.mall.mybatis.mapper.PmsProductDao;
import com.ljh.mall.mybatis.model.PmsProduct;
import com.ljh.mall.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping("/addProduct")
    @ResponseBody
    public String addProduct(Model model, PmsProduct pmsProduct){
        if(pmsProduct.getName() != null && pmsProduct.getProductSn() != null ){
            productService.addProduct(pmsProduct);
            model.addAttribute("product",pmsProduct);
            return model.toString();
        }else {
            model.addAttribute("msg","商品名和货号不能为空！");
            return model.toString();
        }

    }

    @RequestMapping("/deleteProductById")
    @ResponseBody
    public String deleteProductById(Long id){
        if(productService.deleteProductById(id) == 1){
            return "success";
        }else {
            return "false";
        }
    }

    @RequestMapping("/updateProduct")
    @ResponseBody
    public String updateProduct(Model model,PmsProduct pmsProduct){
        productService.updateProductById(pmsProduct);
        model.addAttribute("pmsProduct",pmsProduct);
        return model.toString();
    }

    @RequestMapping("/selectProductById")
    @ResponseBody
    public String selectProductById(Model model,Long id){
        PmsProduct  pmsProduct = productService.selectProductById(id);
        model.addAttribute("pmsProduct",pmsProduct);
        return model.toString();
    }

    @RequestMapping("/showProducts")
    @ResponseBody
    public String showProducts(Model model){
        List<PmsProduct> pmsProducts = productService.showProducts();
        System.out.println("###"+pmsProducts);
        model.addAttribute("pmsProducts",pmsProducts);
        return model.toString();
    }
}
